
#ifndef STATE_NEWMEM_H
#define STATE_NEWMEM_H

#include <vector>

#include "mvc/mycontroller.h"
#include "mvc/mystate.h"

#include "gui/control_member.h"
#include "gui/view_member.h"
#include "gui/model_member.h"
#include "gui/model_bridge.h"

template <class T>
class StateNewMem: public MyState<T> {

  public:
    // ------------------ virtual -------------------- //
    virtual std::string processEvent(ALLEGRO_EVENT* ev) {
        if(ev->type == ALLEGRO_EVENT_KEY_CHAR) {
            // determine action from key
            if(ev->keyboard.keycode == ALLEGRO_KEY_ENTER) {
                ModelBridge* model = (ModelBridge*)this->parent->getModel();
                model->makeMembersPermanent();

                std::vector<MyController*>* temps = this->parent->getTemps();
                temps->clear();

                return "normal";
            }
            else if(ev->keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
                std::vector<MyController*>* temps = this->parent->getTemps();

                // remove newly created members
                for(int i = 0; i < temps->size(); i++) {
                    (*temps)[i]->kill();
                }
                temps->clear();

                MASTER->needRedraw();

                return "normal";
            }
        }
        else if(ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
            std::vector<MyController*>* temps = this->parent->getTemps();

            // create and pass control to a member-controller
            MyController* mem_cont = new ControlMember();
            MyView* mem_view = new ViewMember();
            MyModel* mem_model = new ModelMember();
            ((ModelBridge*)this->parent->getModel())->addMember(mem_model);

            mem_cont->setModel(mem_model);
            mem_cont->setView(mem_view);
            this->parent->addChild(mem_cont); // must come after setting mem_cont's view

            Point point;
            point.setX((double)ev->mouse.x);
            point.setY((double)ev->mouse.y);

            ((ModelMember*)mem_model)->setPoint1(point);
            ((ModelMember*)mem_model)->setPoint2(point);

            if(this->parent == MASTER->getFirstResponder()) {
                MASTER->setFirstResponder(mem_cont);
            }
            MASTER->needRedraw();

            temps->push_back(mem_cont);
        }
    }
};

#endif

